package com.hans.scala.actor


/**
 *
 * Created by Hans on 2014/4/9.
 */

import actors.Actor, Actor._

object ReactExample extends Actor {

  import java.net.{InetAddress, UnknownHostException}

  def act() {
    //    while (true) {//actor 抛出异常后终止
    loop {
      /**
       * 与receive
       */
      react {
        case LookupIp(name, actor) =>
          actor ! LookupResult(name, getIp(name))
//          throw new Exception("test")
        case msg =>
          println("Unhandled message:" + msg)
      }
    }
  }

  def getIp(name: String): Option[InetAddress] = {
    try {
      Some(InetAddress.getByName(name))
    } catch {
      case _: UnknownHostException => None
    }
  }

  def main(args: Array[String]) {
    ReactExample.start()
    ReactExample ! "start..."
    ReactExample ! LookupIp("www.baidu.com", self)
    println(self.receiveWithin(1000) {
      case x => x
    })
    ReactExample ! LookupIp("zjt_hans", self)
    println(self.receiveWithin(1000) {
      case x => x
    })
    ReactExample ! "EXIT"
  }


  //  def act() {
  //    react {
  //      case LookupIp(name, actor) =>
  //        actor ! LookupResult(name, getIp(name))
  //        act()
  //      case "EXIT" =>
  //        println("Name resolver exiting.")
  //      case msg =>
  //        println("Unhandled message:" + msg)
  //        act()
  //    }
  //  }

  case class LookupIp(name: String, respondTo: Actor)

  case class LookupResult(name: String, address: Option[InetAddress])
}
